package edu.kit.aifb.ldstream.learner.query;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.openrdf.model.URI;

import edu.kit.aifb.ldstream.env.Environment;

public class InstanceCache implements Iterable<URI>{

	private File instanceCache = new File(Environment.INSTANCE_CACHE);
	private BufferedWriter writer;
	
	public InstanceCache(URI type){
		if(this.instanceCache.exists()){
			this.instanceCache.delete();
		}
		try {
			this.instanceCache.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.instanceCache.deleteOnExit();
		try {
			this.writer = new BufferedWriter(new FileWriter(this.instanceCache), 1024 * 1024);
		} catch (IOException e) {
			e.printStackTrace();
		}
		init(type);
	}
	
	private void init(URI type){
		InstanceQuery iq = new InstanceQuery(type);
		while(iq.hasNext()){
			try {
				this.writer.write(iq.next().stringValue());
				this.writer.newLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		iq.close();
		closeWriter();
	}
	
	private void closeWriter(){
		try {
			this.writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Iterator<URI> iterator() {
		return new InstanceCacheIterator();
	}
	
	public void close(){
		this.instanceCache.delete();
	}
}
